package com.devehx.wallet.controller;

import com.devehx.wallet.comm.ERC20;
import com.devehx.wallet.comm.Result;
import com.devehx.wallet.comm.TransferParam;
import com.devehx.wallet.comm.WalletKit;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.math.BigInteger;

@Validated
@RestController
@RequestMapping("/eth")
public class Controller {

    /**
     * 查询当前的gas费用
     */
    @RequestMapping("/query_gas")
    public Result<Object> queryGas() {
        return Result.ok(WalletKit.getGasPrice());
    }

    /**
     * 查询nonce
     */
    @RequestMapping("/query_nonce")
    public Result<Object> queryNonce(@NotBlank String address) {
        return Result.ok(WalletKit.getNonce(address));
    }

    /**
     * 创建钱包
     */
    @RequestMapping("/create_wallet")
    public Result<Object> createWallet() {
        return Result.ok(WalletKit.generateWallet());
    }

    /**
     * 转账
     */
    @RequestMapping("/transfer")
    public Result<Object> transfer(TransferParam param) {
        BigInteger amount = param.getAmount();
        String address = param.getAddress();
        String toAddress = param.getToAddress();
        String privateKey = param.getPrivateKey();
        String contactAddress = param.getContactAddress();

        return Result.ok(WalletKit.transfer(contactAddress, address, privateKey, toAddress, amount));
    }

    /**
     * 查询余额
     */
    @RequestMapping("/query_balance")
    public Result<Object> queryBalance(@NotBlank String address, @NotBlank String contactAddress) {
        return Result.ok(ERC20.toUnit(contactAddress, WalletKit.getBalance(address, contactAddress)));
    }

}
